package org.example.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.common.exception.user.CaptchaException;
import org.example.common.exception.user.UserNotExistsException;
import org.example.common.lang.AjaxResult;
import org.example.common.utils.StringUtils;
import org.example.common.utils.UploadUtils;
import org.example.model.User;
import org.example.mapper.UserMapper;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> listAll(){
        return userMapper.listAll();
    }

    @Override
    public List<User> list(int current,int size){
        PageHelper.startPage(current,size);
        List<User> users = userMapper.list(current,size);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo.getList();
    }

    @Override
    public User findById(Integer id){
        User user = userMapper.findById(id);
        return user;
    }

    @Override
    public Boolean addUser(User user){
        userMapper.insert(user);
        return true;
    }

    @Override
    public Boolean delById(Integer id){
        userMapper.delById(id);
        return true;
    }

    @Override
    public Boolean updateById(User user){
        userMapper.updateById(user);
        return true;
    }

    @Override
    public List<User> selectList(int current,int size,String username,Integer age){
        PageHelper.startPage(current,size);
        List<User> users = userMapper.selectList(current,size,username,age);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        return pageInfo.getList();
    }

    @Override
    public void deleteByIds(List<Integer> ids){
        userMapper.deleteByIds(ids);
    }

    @Override
    public int insertList(List<User> users){
        System.out.println(users);
        for(User user:users){
            user.setCreatetime(new Date());
        }
        return userMapper.insertList(users);
    }

    @Override
    public void exportUsersToExcel(List<User> userlist, HttpServletResponse response){
        try{
            Workbook workbook = new XSSFWorkbook();//创建工作簿
            Sheet sheet = workbook.createSheet("用户列表");//创建工作表

            CellStyle cs = setSimpleCellStyle(workbook);

            //创建表头
            Row headerRow = sheet.createRow(0);

            Cell headerCell0 = headerRow.createCell(0);
            headerCell0.setCellStyle(cs);
            headerCell0.setCellValue("id");

            Cell headerCell1 = headerRow.createCell(1);
            headerCell1.setCellStyle(cs);
            headerCell1.setCellValue("姓名");

            Cell headerCell2 = headerRow.createCell(2);
            headerCell2.setCellStyle(cs);
            headerCell2.setCellValue("密码");

            Cell headerCell3 = headerRow.createCell(3);
            headerCell3.setCellStyle(cs);
            headerCell3.setCellValue("性别");


//            headerRow.createCell(0).setCellValue("id");
//            headerRow.createCell(1).setCellValue("姓名");
//            headerRow.createCell(2).setCellValue("密码");
//            headerRow.createCell(3).setCellValue("性别");

            //填充数据
            int rowNum = 1;
            for(User user : userlist){
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(user.getId());
                row.createCell(1).setCellValue(user.getUsername());
                row.createCell(2).setCellValue(user.getPassword());

                String sex;
                if(user.getSex().equals(0)){
                    sex = "男";
                } else if (user.getSex().equals(1)) {
                    sex = "女";
                }else{
                    sex = "未知";
                }
                row.createCell(3).setCellValue(sex);
            }

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=users.xlsx");

            //将工作簿写入响应流
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();

        }catch(Exception e){
            e.printStackTrace();
        }

    }

    // 设置简单的cell样式@return

    public CellStyle setSimpleCellStyle(Workbook wb){
        CellStyle cs = wb.createCellStyle();
        cs.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.getIndex());//背景色
        cs.setFillPattern(FillPatternType.SOLID_FOREGROUND);//背景色填充样式
        cs.setAlignment(HorizontalAlignment.CENTER);//水平居中

        return cs;
    }

    @Override
    public void uploadImg(Integer id, String avatar){
       User result = userMapper.findById(id);
       if(result == null){
           System.out.println("用户数据不存在");
       }

        userMapper.uploadImg(id,avatar);
    }

    @Override
    public String login(User user){

        try {
            User userExistName = userMapper.findByName(user.getUsername());

            if(userExistName != null){
                String userExistPsw = userMapper.findPswByName(user.getUsername());
               if(userExistPsw.equals(user.getPassword())){
                   return user.getUsername()+"登录成功！";
               }else{
                   return "密码错误";
               }
            }else{
                return "用户名不存在";
            }
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }
    }
    @Override
    public User login2(String username,String password){



        //验证码校验
//        if(){
//            throw new CaptchaException();
//
//        }
        //用户名或密码为空  错误
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            throw new UserNotExistsException();
        }

        User user = userMapper.findByName(username);
        if(user == null){
            throw new UserNotExistsException();
        }
        return user;
    }
    @Override
    public String register(User user){
        try {
            User userExist = userMapper.findByName(user.getUsername());
            System.out.println("666");
            System.out.println(userExist);
            if(user.getUsername() == ""){
                System.out.println("1111");
               return "用户名为空";
            }else if(user.getPassword().equals("")){
                return "密码为空";
            }else if(userExist != null){
                return "该用户已经存在";
            }else{
                userMapper.insert(user);
                return "注册成功";
            }

        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }
    }
    @Override
    public User findByName(String name){
        return userMapper.findByName(name);
    }
}
